#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "lm4f120h5qr.h"

extern volatile uint16_t DisplayPWM;

//***************************************************************************
// Initialize the Timer0A timer to a given count.
// Used for Display timer
// See page 694 of tm4c1233h6pm.pdf for more information
// See line 683 of lm4f120h5qr.h
//***************************************************************************
void initializeTimer0A(uint32_t count)
{
	SYSCTL_RCGCTIMER_R |= SYSCTL_RCGCTIMER_R0;	// Enable Timer Clock
	TIMER0_CTL_R = 0x0000;	// Disable timer
	TIMER0_CFG_R = 0x00;	// Set to 32-bit configuration

	// Set timer to periodic, count up mode with interrupt enabled
	TIMER0_TAMR_R = 0x32;

	TIMER0_TAILR_R = count;
	TIMER0_IMR_R = 0x0001;	// Interrupt Mask
	TIMER0_CTL_R = 0x01;	// Enable timer

	NVIC_EN0_R |= 0x00080000;	// Set EN0 for Timer0A
}

//***************************************************************************
// Initialize the Timer1A timer to a given count.
// Used for RTC
// See page 695 of tm4c1233h6pm.pdf for more information
// See line 683 of lm4f120h5qr.h
//***************************************************************************
void initializeTimer1A(uint32_t count)
{
	SYSCTL_RCGCTIMER_R |= SYSCTL_RCGCTIMER_R1;	// Enable Timer Clock
	TIMER1_CTL_R = 0x0000;	// Disable timer
	TIMER1_CFG_R = 0x01;	// Set to RTC configuration

	// Write value to Match Register? p.695 #4????????????????????????

	TIMER1_CTL_R = 0x0012;
	TIMER1_IMR_R = 0x0008;	// Interrupt Mask
	TIMER1_CTL_R = 0x01;	// Enable timer

	NVIC_EN1_R |= 0x00000002;	// Set EN1 for Timer0A
}

void Timer0AIntHandler(void)
{
	if (DisplayPWM == 256) {
		DisplayPWM = 0;
	}
	DisplayPWM++;		// Set flag

	NVIC_DIS0_R &= 0x00000000;	// Clear interrupt
	// NOTE: THIS CLEARS ALL INTERRRUPTS! FIX THIS!
}

void Timer1AIntHandler(void)
{

	NVIC_DIS1_R &= 0x00000000;	// Clear interrupt
}
